const express = require('express');
const router = express.Router();
const adminService = require('../../services/adminService');
const adminAuth = require('../../middleware/adminAuth');
const { checkPermission } = require('../../middleware/permission');

/**
 * 管理员登录
 */
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    const clientIp = req.ip || req.connection.remoteAddress || req.socket.remoteAddress;
    const result = await adminService.login(username, password, clientIp);

    res.json({
      success: true,
      message: '登录成功',
      data: result
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 获取当前管理员信息
 */
router.get('/profile', adminAuth, async (req, res) => {
  try {
    const admin = await adminService.getAdminById(req.adminId);
    
    res.json({
      success: true,
      data: {
        id: admin.id,
        username: admin.username,
        email: admin.email,
        realName: admin.realName,
        avatar: admin.avatar,
        status: admin.status,
        lastLoginAt: admin.lastLoginAt,
        roles: admin.roles.map(role => ({
          id: role.id,
          name: role.name,
          displayName: role.displayName
        })),
        permissions: admin.roles.reduce((perms, role) => {
          role.permissions.forEach(permission => {
            if (!perms.find(p => p.id === permission.id)) {
              perms.push({
                id: permission.id,
                name: permission.name,
                resource: permission.resource,
                action: permission.action
              });
            }
          });
          return perms;
        }, [])
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取管理员信息失败',
      error: error.message
    });
  }
});

/**
 * 更新管理员个人信息
 */
router.put('/profile', adminAuth, async (req, res) => {
  try {
    const { email, phone, realName, avatar } = req.body;
    
    await adminService.updateAdmin(req.adminId, {
      email,
      phone,
      realName,
      avatar
    }, req.adminId);

    res.json({
      success: true,
      message: '个人信息更新成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 修改密码
 */
router.put('/password', adminAuth, async (req, res) => {
  try {
    const { oldPassword, newPassword } = req.body;
    
    if (!oldPassword || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '旧密码和新密码不能为空'
      });
    }

    if (newPassword.length < 6) {
      return res.status(400).json({
        success: false,
        message: '新密码长度不能少于6位'
      });
    }

    // 验证旧密码
    const isValidPassword = await req.admin.verifyPassword(oldPassword);
    if (!isValidPassword) {
      return res.status(400).json({
        success: false,
        message: '旧密码错误'
      });
    }

    // 更新密码
    await adminService.resetPassword(req.adminId, newPassword, req.adminId);

    res.json({
      success: true,
      message: '密码修改成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 登出
 */
router.post('/logout', adminAuth, async (req, res) => {
  try {
    // 这里可以实现token黑名单机制
    // 目前只是返回成功响应，客户端删除token即可
    
    res.json({
      success: true,
      message: '登出成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '登出失败',
      error: error.message
    });
  }
});

module.exports = router;